#include <iostream>
#include <fstream>
#include <sstream>
#include <unordered_map>
#include <utility>
#include <chrono>
using std::string;
using std::unordered_map;
using std::pair;
using std::cout;
using std::cin;
using std::endl;
using std::ifstream;
using std::ofstream;
using std::istringstream;

//字典类
class Dict {
public:
    //从文件读进对象
    void read_by_file(const string& filename) {
        ifstream ifs(filename);
        if (!ifs) {
            cout << "do not hava this file " << endl;
        }
        //循环行读
        string line;
        while (std::getline(ifs, line)) {
            //用字符串流循环拿出一个并解析
            string word;
            istringstream iss(line);
            while (iss >> word) {
                //更新字符串
                update_word(word);
                //将字符串插入字典
                push_word(word);
            }
        }
    }
    //从对象写出文件
    void write_in_file(const string& filename) {
        //打开一个写文件
        ofstream ofs(filename);
        if (!ofs) {
            cout << "open " << filename << "failed" << endl;
        }
        //遍历字典中的m_map并写入文件
        // size_t total = 0;
        for (auto e : m_map) {
            // total += e.second;
            ofs << e.first << " : " << e.second << endl;
        }
        // cout << "total = " << total << endl;
    }
private:
    //判断是不是字母
    bool is_char(char ch) {
        return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');
    }
    //更新字符串，删除无效的字符
    string& update_word(string& word) {
        auto it = word.begin();
        while (it < word.end()) {
            //不是字母就擦除这个字符
            if (is_char(*it) == false) {
                it = word.erase(it);
                continue;
            }
            it++;
        }
        return word;
    }
    //将不为空的字符插入字典
    bool push_word(const string& word) {
        if (word.size()) {
            m_map[word]++;
            return true;
        }
        return false;
    }
private:
    unordered_map<string, size_t> m_map;
};

void test() {
    Dict dict;
    // time_t start = time(NULL);
    string read_file_name("The_Holy_Bible.txt");
    string write_file_name("Holy.txt");
    dict.read_by_file(read_file_name);
    dict.write_in_file(write_file_name);
    // time_t end = time(NULL);
    // cout << "time = " << end - start << endl;

}
int main() {
    // 记录开始时间点
    auto start = std::chrono::high_resolution_clock::now();
    test();
    // 记录结束时间点
    auto end = std::chrono::high_resolution_clock::now();
    // 计算时间差，并将其转换为毫秒
    auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();

    std::cout << "The operation took " << duration << " milliseconds." << std::endl;
    return 0;
}